<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/8/8
 * Time: 23:20
 */

use App\Models\UserLog;
use Dcat\Admin\Admin;
use Carbon\Carbon;
use App\Models\AdminUser;
use Large\Zhengdada\Functions;


/***
 *  * 获取时时汇率
 * @return bool
 */
function getRate(){
    $ratePath = public_path('rate.text');

    if (verifyFileTime($ratePath)){
        $rate = file_get_contents($ratePath);
    }else{
        file_put_contents($ratePath, queryRate());
        $rate = file_get_contents($ratePath);
    }

    $str = $rate - ($rate * 0.018);
    return empty($rate) ? 6.4 : getNumberFormat($str, 4);
}


/***
 * 验证文件是不是存在
 * @param $dir
 * @return bool
 */
function verifyFilePath($dir) {
    $url = env('APP_URL') . '/' . $dir;
    if (! @fopen($url, 'r')) {
        return false;
    }
    return true;
}

/***
 * 判断文件是不是过期了。
 * @param $file 文件路径
 * @return bool
 */
function verifyFileTime($file){

    if (!is_file($file)) return false;

    // 函数返回文件内容的上次修改时间。
    $res = filemtime($file);

    if (time() - $res > 300){
        return false;
    }
    return true;
}


/***
 * 请求远程汇率数据
 * @return float
 */
function queryRate(){

    $url = 'http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=54098&sign=64499a3b39abcbcb5709712c4039cf54';

    $rate = json_decode(file_get_contents($url), true);

    if ($rate['success'] == 1){
        return getNumberFormat($rate['result']['rate'] - ($rate['result']['rate'] * 0.015), 4);
    }
    return 6.6;
}


/***
 * 验证投出时间
 * 周五21点 - 周六02点后系统结算中，不可出投入
 */
function verifyWithdrawTime(){
    $t1 = Carbon::now()->subWeek(0)->endOfWeek(-2)->toDateString();
    $t2 = Carbon::now()->subWeek(0)->endOfWeek(-1)->toDateString();
    if (($t1 == date('Y-m-d') && date('H') >= '21') || ($t2 == date('Y-m-d') && date('H') <= '02')){
        return false;
    }
    return true;
}

/***
 * 验证用户角色，查询如果有，不拦截
 * @param $id 用户ID
 * @param int $type 判断方式 ， ==  !=
 * @param int $mode 返回什么
 */
function verifyUserRole($id, $mode = true, $type = '!='){
    $user = AdminUser::whereHas('roles', function($q) use ($type){
        $q->where('id', $type, 2);
    })->find($id);

    //dd($user);
    if (!$user){
        $res = explode('/', request()->path());
        if (in_array(count($res), [4, 5])){
            $url = '/'.$res[0].'/'.$res[1].'/'.$res[2];
        }else{
            $url = '/'.$res[0].'/'.$res[1];
        }

        if ($mode){
            return Admin::script(
                <<<JS
                Dcat.error('参数错误');
                return setTimeout(function () {
                    Dcat.reload('{$url}');
                }, 1500);
JS
            );
        }else{
            return false;
        }
    }else{
        return true;
    }
}


/***
 * 写入用户操作日志
 * @param $notes
 * @param string $log_title
 */
function recordUserLog($log_title, $notes = '...') {
    $data['user_id'] = Admin::user()->id;
    $data['log_title'] = $log_title;
    $data['notes'] = $notes;
    $data['prefix'] = explode('/',request()->path())[0];
    $data['log_ip'] = request()->ip();
    $data['log_url'] = request()->url();

    $result = new UserLog($data);
    $result->save();
}





/***
 * 查询用户下级
 * @param $id 自身ID
 */
function queryUsersLowerLevel($id){
    $user = AdminUser::whereHas('roles', function($q){
        $q->where('id', 2);
    })->get();

    $result = Functions::getTreeData($user, $id, 'tjr_id');
    return collect($result)->pluck('id')->toArray();
}


/***
 * 返回计算后的返佣金金额
 * @param $form  申请投投出额对象
 * @return float|int
 */
function meterUserFee($form) {
    $sxf = \Config::get('app.sxf');

    $newMoney = '';
    if ($form->amount_type == 2) {
        $newMoney = $form->usd_amount * $sxf;
    }
    return round($newMoney, 4) ?? 0;
}


/***
 * 获取周一时间
 * @return Carbon
 */
function getStartOfWeek(){

    return Carbon::now()->startOfWeek()->toDateTimeString();
}

/***
 * 获取周日时间
 * @param string $num 定义周几
 * @return Carbon
 */
function getEndOfWeek($num = 0){

    return Carbon::now()->endOfWeek($num)->toDateTimeString();
}


/***
 * 获取本月的第一天
 * @param int $num 0:为本月，1为上月，-1为本月加一月
 * @return string
 */
function getFirstOfMonth($num = 0){
    return Carbon::now()->subMonth($num)->firstOfMonth()->toDateTimeString();
}

/***
 * 获取本月的最后一天
 * @param int $num 0:为本月，1为上月，-1为本月加一月
 * @return string
 */
function getLastOfMonth($num = 0){

    return Carbon::now()->subMonth($num)->lastOfMonth()->toDateTimeString();
}


/***
 * 数字留几位小数点
 * @param $num | string   数字
 * @param int $folat  几个小数点
 * @param string $type  用什么隔开
 * @param string $extent
 * @return mixed
 */
function getNumberFormat($num, $folat = 2, $type = '.', $extent = ''){

    return number_format($num, $folat, $type, $extent);
}


/***
 * 搜索获取时间
 * @return mixed
 */
function getFilterDate($num = 0){
    $t = request()->input('created_at');
    if (!$t){
        $t['start'] = getStartOfWeek();
        $t['end']   = getEndOfWeek($num);
    }
    if (!$t['start']) {
        $t['start'] = getStartOfWeek();
    }
    if (!$t['end']) {
        $t['end']   = getEndOfWeek($num);
    }
    return $t;
}


/***
 * 修改用户推荐人，等级为0的排除
 * @param $user 传入用户数据
 * @return mixed
 */
function changeUserTjrId(&$user){
    foreach($user as $k=>$v){
        $v->tjr_id = judgeUserMoney($v);
    }
    return $user;
}

/***
 * 查询用户推荐人等级是不是为0，如果是往上找,直到公司帐号
 * @param $user 传入用户数据
 * @return mixed
 */
function judgeUserMoney($user){

    $newUsers = \Cache::get('users') ?? $user;
    $newUser = $newUsers->where('id', $user->tjr_id)->first();
    if (!$newUser){
        return $user->id;
    }
    if ($newUser->users_leader_id == 0 && $newUser->investment_amount <= 0){
        return judgeUserMoney($newUser);
    }else{
        return $newUser->id;
    }
}



function getUserTree2($array, $fid = 0, $level = 0, $ib = 0) {
    $column = [];
    foreach ($array as $key => $vo) {
        if ($vo['tjr_id'] == $fid) {
            if($vo['users_leader_id'] > $ib || $vo['users_leader_id'] == $ib){
                //$column['tj'][$vo['user_id']] = $vo['user_id'];
                $column['nlt_id_'.$vo->id] = $vo->id;
                continue;
            }
            $column[] = $vo->id;
            //$column['xj'][] = $vo['user_id'];
            $column = array_merge($column, getUserTree2($array, $vo->id, $level + 1, $ib));
        }
    }

    return $column;
}


function get_key_type($arr, $type = 1){
    if(empty($arr))
        return false;
    unset($new_array);
    $new_array = [];
    foreach($arr as $k=>$v){
        if($type == 1){
            if(is_numeric($k)){
                $new_array[$k] = $v;
            }
        }
        if($type == 2){
            if(!is_numeric($k)){
                $new_array[$k] = $v;
            }
        }

    }
    return $new_array;
}



/***
 * 每周最后指定日期
 * @param int $num
 * @return array|string
 */
function meiWeek($num = 9, $and = '-8'){
    $arr = [];
    for ($i=0; $i <=$num; $i++) {
        $arr[] = Carbon::now()->subWeek($i)->endOfWeek($and)->toDateString();

    }
    return $arr;
}



function getLang(){

    return config('app.locale');
}



/***
 * @param $str 获取数组 里的K 和 V
 * 返回  K V
 */
function getArrayKeyToValue($str){

    if(!is_array($str)){
        return ['' , $str];
    }
    return [array_keys($str)[0] , array_values($str)[0]];
}


